package com.chat.dao;

import com.chat.entity.Message;
import com.chat.entity.User;
import com.chat.util.HibernateUtil;
import com.chat.util.SpringUtil;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class MessageDaoImp implements MessageDao{
    @Override
    public List<Message> getMessages(User sourceUser, User targetUser) {
        Session session=HibernateUtil.getCurrentSession();
        Query<Message> query=session.createQuery("from Message " +
                "where sourceUser=:sourceUser and targetUser=:targetUser",Message.class);

        query.setParameter("sourceUser",sourceUser);
        query.setParameter("targetUser",targetUser);

        List<Message> list=query.list();

        for(Message msg:list){
            session.evict(msg);
        }

        return list;
    }

    @Override
    public void deleteMessage(long msgId) {
        Session session=HibernateUtil.getCurrentSession();
        Message message=session.get(Message.class,msgId);

        if (message==null) return;

        session.delete(message);
    }

    @Override
    public void saveMessage(Message msg) {
        Session session=HibernateUtil.getCurrentSession();
        session.save(msg);
    }
}
